package autoTest.request;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import autoTest.command.ErrorCode;
import autoTest.command.Params;
import autoTest.device.Platform;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class QuerryBlackListPart extends RequestPart {
	private static final long serialVersionUID = 2271797150647771300L;
	
	protected void doResponse(HttpServletResponse resp, int code, String result) throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");  
		resp.setContentType("text/plain");
		resp.setStatus(HttpServletResponse.SC_OK);
		PrintWriter pWriter = resp.getWriter();
		JSONObject joRet = new JSONObject();
		joRet.put(Params.CODE, code);
		joRet.put(Params.CONTENT, result);
		pWriter.println(joRet.toString());  
	}

	@Override protected void process(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	String platformStr = req.getParameter(Params.PLAT_FORM);
    	String typeStr = req.getParameter(Params.TYPE);
    	
    	System.out.println("[doResponse] platformStr:" + platformStr + ", typeStr:" + typeStr);
    	
    	int typeValue = -1;
    	try {
    		typeValue = Integer.valueOf(typeStr);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	Platform pf = Platform.valueStrOf(platformStr);
    	if (!(typeValue == 0 || typeValue == 1)) {
    		doResponse(resp, ErrorCode.ERR_PARAM_ERROR, null);
    		return;
    	}
    	List<Platform> allPf = new ArrayList<Platform>();
    	if (pf == null) {
    		allPf.add(Platform.ANDROID);
    		allPf.add(Platform.IOS);
    		allPf.add(Platform.WINDOWS);
    	} else {
    		allPf.add(pf);
    	}
    	
    	JSONArray retJa = new JSONArray();
    	for (Platform elePf : allPf) {
        	Set<String> result = null;;
        	switch(typeValue) {
        	case 0:
        		result = SetBlackListPart.getBlackListDirByPlatform(elePf);
        		break;
        	case 1:
        		result = SetBlackListPart.getBlackListCaseByPlatform(elePf);
        		break;
        	}
    		if (result == null) {
    			result = new HashSet<String>();
    		}
        	JSONObject jo = new JSONObject();
        	jo.put(Params.PLAT_FORM, elePf.valueStr());
        	JSONArray joJa = new JSONArray();
        	for (String ele : result) {
        		joJa.add(ele);
        	}
        	jo.put(Params.BLACKLIST, joJa);
        	retJa.add(jo);
    	}
    	doResponse(resp, ErrorCode.SUCCESS, retJa.toString());
	}
}
